package finelProject.servlets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

import finelProject.MyAppConstants;

/**
 * Servlet implementation class FollowUser
 */
public class FollowUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FollowUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			Context context = new InitialContext();
    		BasicDataSource ds = (BasicDataSource)context.lookup(MyAppConstants.DB_DATASOURCE);
    		Connection conn = ds.getConnection();
			String uri = request.getRequestURI();
		
			//get the names of the follower and the followe.
			String followername = uri.substring(uri.indexOf(MyAppConstants.INSERT) + MyAppConstants.FOLLOW.length() + 1,uri.lastIndexOf(MyAppConstants.SEPARATOR));
			String followename = uri.substring(uri.lastIndexOf(MyAppConstants.SEPARATOR)+1);
			followername = followername.replaceAll("\\%20", " ");
			followename = followename.replaceAll("\\%20", " ");
			
			//insert the name into the FOLLOW table in the DB
			PreparedStatement stmt;
			try{
			stmt = conn.prepareStatement(MyAppConstants.INSERT_INTO_FOLLOW);
			stmt.setString(1, followername);
			stmt.setString(2, followename);
			stmt.executeQuery();
			
			} catch (SQLException e) {
				getServletContext().log("Error while INSERT to FOLLOW", e);
				response.sendError(500);//internal server error
			}
			conn.close();
		}
		catch(SQLException | NamingException e){
			getServletContext().log("Error while closing connection", e);
    		response.sendError(500);//internal server error
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
